#include "uart.h"
bit busy;


//封装串口通道
void UartChannel(char ch){
		ACC = P_SW1;
	if(ch == 0){//默认通道 P3.0 P3.1
    ACC &= ~(S1_S0 | S1_S1); 
	  T2L = (65536 - (FOSC/4/BAUD_9600));   //设置波特率重装值
    T2H = (65536 - (FOSC/4/BAUD_9600))>>8;
	}
	else if(ch == 1){//通道一 P3.6 P3.7
		ACC |= (S1_S0);
		ACC &= ~S1_S1;
		T2L = (65536 - (FOSC/4/BAUD_57600));   //设置波特率重装值
    T2H = (65536 - (FOSC/4/BAUD_57600))>>8;
	}
	else if(ch == 2){//通道二 P1.6 P1.7
		ACC |= (S1_S1);
		ACC &= ~S1_S0;	
		T2L = (65536 - (FOSC/4/BAUD_115200));   //设置波特率重装值
    T2H = (65536 - (FOSC/4/BAUD_115200))>>8;
	}else{//默认通道 P3.0 P3.1
		 ACC &= ~(S1_S0 | S1_S1);    //S1_S0=0 S1_S1=0
		T2L = (65536 - (FOSC/4/BAUD_9600));   //设置波特率重装值
    T2H = (65536 - (FOSC/4/BAUD_9600))>>8;
	}
	 P_SW1 = ACC;  
}

void UartSystem(){
	UartChannel(0);
#if (PARITYBIT == NONE_PARITY)
    SCON = 0x50;                //8位可变波特率
#elif (PARITYBIT == ODD_PARITY) || (PARITYBIT == EVEN_PARITY) || (PARITYBIT == MARK_PARITY)
    SCON = 0xda;                //9位可变波特率,校验位初始为1
#elif (PARITYBIT == SPACE_PARITY)
    SCON = 0xd2;                //9位可变波特率,校验位初始为0
#endif

//    T2L = (65536 - (FOSC/4/BAUD));   //设置波特率重装值
//    T2H = (65536 - (FOSC/4/BAUD))>>8;
    AUXR = 0x14;                //T2为1T模式, 并启动定时器2
    AUXR |= 0x01;               //选择定时器2为串口1的波特率发生器
    ES = 1;                     //使能串口1中断
    EA = 1;
}
/*----------------------------
UART 中断服务程序
-----------------------------*/
char ch=0;
void Uart() interrupt 4 using 1
{
    if (RI)
    {
        RI = 0;                 //清除RI位
        ch = SBUF;              //P0显示串口数据
				SendData(ch+1); 	
    }
    if (TI)
    {
        TI = 0;                 //清除TI位
        busy = 0;               //清忙标志
    }
}
/*----------------------------
发送串口数据
----------------------------*/
void SendData(BYTE dat)
{
    while (busy);               //等待前面的数据发送完成
    ACC = dat;                  //获取校验位P (PSW.0)
    if (P)                      //根据P来设置校验位
    {
#if (PARITYBIT == ODD_PARITY)
        TB8 = 0;                //设置校验位为0
#elif (PARITYBIT == EVEN_PARITY)
        TB8 = 1;                //设置校验位为1
#endif
    }
    else
    {
#if (PARITYBIT == ODD_PARITY)
        TB8 = 1;                //设置校验位为1
#elif (PARITYBIT == EVEN_PARITY)
        TB8 = 0;                //设置校验位为0
#endif
    }
    busy = 1;
    SBUF = ACC;                 //写数据到UART数据寄存器
}
/*----------------------------
发送字符串
----------------------------*/
void SendString(char *s)
{
    while (*s)                  //检测字符串结束标志
    {
        SendData(*s++);         //发送当前字符
    }
}
